package com.zhouyer.sqlSession;

import com.zhouyer.pojo.Configuration;
import com.zhouyer.pojo.MappedStatement;
import com.zhouyer.pojo.SqlCommandType;

import java.beans.IntrospectionException;
import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.List;

public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws SQLException, IllegalAccessException, IntrospectionException, InstantiationException, NoSuchFieldException, InvocationTargetException, ClassNotFoundException {
        // 调用SimpleExecutor中的query方法进行查询
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<Object> objects = simpleExecutor.query(configuration, mappedStatement, params);
        return (List<E>) objects;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws SQLException, IllegalAccessException, IntrospectionException, InstantiationException, ClassNotFoundException, InvocationTargetException, NoSuchFieldException {
        List<Object> objects = selectList(statementId, params);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        } else {
            throw new RuntimeException("查询结果为空或者返回结果过多");
        }
    }

    /**
     * 新增记录
     *
     * @param statementId
     * @param params
     * @return
     */
    @Override
    public int insert(String statementId, Object... params) throws ClassNotFoundException, SQLException, IllegalAccessException, NoSuchFieldException {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        return simpleExecutor.update(configuration, configuration.getMappedStatementMap().get(statementId), params);
    }

    /**
     * 更新记录
     *
     * @param statementId sql标示
     * @param params      更新的记录
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     * @throws IllegalAccessException
     * @throws NoSuchFieldException
     */
    @Override
    public int update(String statementId, Object... params) throws ClassNotFoundException, SQLException, IllegalAccessException, NoSuchFieldException {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        return simpleExecutor.update(configuration, configuration.getMappedStatementMap().get(statementId), params);
    }

    /**
     * 删除记录
     *
     * @param statementId sql标示
     * @param params      参数
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     * @throws IllegalAccessException
     * @throws NoSuchFieldException
     */
    @Override
    public int delete(String statementId, Object... params) throws ClassNotFoundException, SQLException, IllegalAccessException, NoSuchFieldException {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        return simpleExecutor.update(configuration, configuration.getMappedStatementMap().get(statementId), params);
    }

    /**
     * 根据传入的类获取代理对象
     *
     * @param mapperClass
     * @return
     */
    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        // mapper代理对象
        return (T) Proxy.newProxyInstance(mapperClass.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            // 只要调用mapper接口里面的方法就会调用invoke方法
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 这里需要调用上面的查询方法
                // 1、statementId怎么来； 以IUserMapper为主，我们通过将该接口的全限定名和与mapper.xml中的namespace保持一直，接口的方法名与.xml中的标签id保持一直
                // 即 接口全限定名.接口的方法名 = .xml中namespace.id  = statementId
                // 2、参数 就是args
                // 3、怎么判断调用selectOne还是selectList 通过判断接口中方法的返回类型
                // 获取调用接口的方法名
                String methodName = method.getName();
                // 获取该接口的全限定名
                String className = method.getDeclaringClass().getName();
                // statementId
                String statementId = String.format("%s.%s", className, methodName);

                //判断调用哪个方法
                return invokeTargetMethod(method, statementId, args);
            }
        });
    }

    private Object invokeTargetMethod(Method method, String statementId, Object[] args) throws IllegalAccessException, ClassNotFoundException, IntrospectionException, InstantiationException, SQLException, InvocationTargetException, NoSuchFieldException {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        switch (SqlCommandType.getSqlCommandTypeByTag(mappedStatement.getSqlCommandType())) {
            case SELECT:
                //判断调用哪个方法
                Type genericReturnType = method.getGenericReturnType();
                if (genericReturnType instanceof ParameterizedType) {
                    return selectList(statementId, args);
                }
                return selectOne(statementId, args);
            case INSERT:
                return insert(statementId, args);
            case DELETE:
                return delete(statementId, args);
            case UPDATE:
                return update(statementId, args);
            default:
                break;
        }
        return null;
    }
}
